import React, { useState, useEffect } from 'react';
import { Text, View, Image, openGroupCreate, onOpenGroupCreate, deviceIsSupportThingModel, beginEvent, openZigbeeLocalGroup, useQuery } from '@ray-js/ray';
import { NavBar, Button, Icon } from '@ray-js/smart-ui';
import styles from './index.module.less';
import Strings from '@/i18n';
import res from '@/res/index';
import Slider from '@ray-js/components-ty-slider'
import CountdownActionSheet from '@ray-js/countdown-action-sheet';
import { schemaMap } from '@/devices/schema'
import { useDevice, useProps } from '@ray-js/panel-sdk';
import { devices } from '@/devices';
import { getCachedLaunchOptions } from '@/api/getCachedLaunchOptions';
import { isNull, isNumber } from 'lodash-es';
import { GroupEditQuery, Props } from './index.type';
import { getZigbeeLocalGroupRelation } from '@ray-js/ray';

const {
  switch_led_1,
  bright_value_1,
  countdown_1,
} = schemaMap;
type ResGetZigbeeLocalIds = {
  locals: Array<{
    /**
     * 功能点 code
     */
    code: string;
    /**
     * 排序
     */
    order: number;
    /**
     * 设备端用到的群组 localId
     */
    localId: string;
    /**
     * 面板使用的 code，用来做映射，值以 300 为前缀，例如3001
     */
    categoryCode: string;
  }>;
};
// const devId = useDevice(d => d.devInfo.devId);
const { deviceId, groupId, devInfo  } = getCachedLaunchOptions()?.query ?? {};
export const Home: React.FC = props => {
  // const actions = useActions();
  const power = useProps(props => props.switch_led_1);
  const bright = useProps(props => props.bright_value_1);
  const countdown = useProps(props => props.countdown_1);
  const [active, setActive] = useState(1);
  const { code, localId, categoryCode, groupIcon }: GroupEditQuery = useQuery();
  const [value, setValue] = useState(bright);
  const [show, setShow] = useState(false);
  const CATEGORY_CODES = {
    light: [
      'syzmqd',
      'syzmkz',
      'dj',
      'zmqd',
      'dd',
      'xdd',
      'mbd',
      'txd',
      'sxd',
      'gyd',
      'fsd',
      'tgq',
      'ld',
    ],
    curtain: ['zig_clkg', 'zig_cl', 'clkg', 'cl'],
  };
  // const [countdown, setCountdown] = useState(0);
  useEffect(()=>{
    setValue(Math.round(bright/10));
  },[bright])
  const getZigbeeLocalIds = (): Promise<ResGetZigbeeLocalIds> => {
    const devId = getCachedLaunchOptions()?.query?.deviceId;
    // @ts-ignore
    return getZigbeeLocalGroupRelation({ devId });
    // return {
    //   locals: [
    //     {
    //       categoryCode: '3001',
    //       code: 'switch_1',
    //       localId: '10020',
    //     },
    //     {
    //       categoryCode: '3002',
    //       code: 'switch_2',
    //       localId: '10040',
    //     },
    //     {
    //       categoryCode: '3003',
    //       code: 'switch_3',
    //       localId: '10060',
    //     },
    //     {
    //       categoryCode: '3004',
    //       code: 'switch_4',
    //       localId: '10080',
    //     },
    //     {
    //       categoryCode: '3005',
    //       code: 'switch_5',
    //       localId: '10100',
    //     },
    //     {
    //       categoryCode: '3006',
    //       code: 'switch_6',
    //       localId: '10120',
    //     },
    //     {
    //       categoryCode: '3007',
    //       code: 'switch_7',
    //       localId: '10140',
    //     },
    //     {
    //       categoryCode: '3008',
    //       code: 'switch_8',
    //       localId: '10160',
    //     },
    //   ],
    // };
  };
  const open = React.useCallback(() => {
    // setShow(true);
  }, []);

  const hide = React.useCallback(() => {
    setShow(false);
  }, []);
  const handlePower = () =>{
    const cmd = {}
    if(power){
      cmd[switch_led_1.code] = false;
      devices.common.publishDps(cmd, {immediate: true})
    }else{
      cmd[switch_led_1.code] = true;
      devices.common.publishDps(cmd, {immediate: true})
    }
  }
  const handleStop = React.useCallback(() => {
    hide();
    const cmd ={};
    cmd[countdown_1.code] = 0;
    devices.common.publishDps(cmd, {immediate: true})
  }, []);

  const handleOK = React.useCallback<React.ComponentProps<typeof CountdownActionSheet>['onOk']>(
    data => {
      hide();
      if (data.mode === 'set') {
        const cmd = {};
        cmd[countdown_1.code] = data.value;
        devices.common.publishDps(cmd, {immediate: true})
      }
    },
    []
  );
  const handleChange = (value)=>{
    const cmd = {};
    setValue(value);
    cmd[bright_value_1.code] = value * 10;
    devices.common.publishDps(cmd, {immediate: true})
  }
  const handleGroup = async()=>{
    // onOpenGroupCreate(()=>{
    //   console.log('创建群组保存完成')
    // })
    // openGroupCreate({
    //   deviceId
    // }).then(() => {
    //   console.log('调用成功打开创建群组页面');
    // });
    const category = await getZigbeeLocalIds();
    console.log('====>',category);
    openZigbeeLocalGroup({ deviceId, localId, categoryCode: '3001', codes: CATEGORY_CODES.light.join(',') });
  }
  return (
    <View className={styles.view}>
      <NavBar leftText=" " />
      <View
        className={styles.content}
        onClick={() => {
          // actions.switch_1.toggle();
        }}
      >
        <View className={styles.tab}>
          <View className={`${styles.tabItem} ${active === 1 ? styles.active : ''}`} onClick={()=>{setActive(1)}}>
            <Text>{Strings.getLang('knobControl')}</Text>
          </View>
          <View  className={`${styles.tabItem} ${active === 0 ? styles.active : ''}`} onClick={()=>{setActive(0)}}>
            <Text>{Strings.getLang('sceneSwitch')}</Text>
          </View>
        </View>
        <View className={styles.groupContainer} onClick={handleGroup}>
          <View className={styles.group}>
            <Image src={res.group} className={styles.icon}></Image>
            <Text className={styles.groupName}>{Strings.getLang('group')}</Text>
            <Image src={res.arrow} className={styles.arrow}></Image>
          </View>
        </View>
        <View className={styles.sliderContainer}>
          <View style={{position: 'relative', height: '249px',overflow: 'hidden'}}>
            <Slider
              isVertical
              min={0}
              max={100}
              value={value}
              onAfterChange={(value)=>{handleChange(value)}}
              maxTrackWidth="150px"
              maxTrackHeight="250px"
              maxTrackRadius="16px"
              thumbRadius= '16px'
              minTrackWidth="150px"
              minTrackRadius="16px"
              // minTrackHeight="22px"
              thumbWidth="0px"
              thumbHeight="1px"
              hideThumbButton={true}
              minTrackColor="#FFCE6B"
              enableTouch={true}
              style={{overflow: 'hidden'}}
            />
            <Text className={styles.percent}>{isNull(value) ? 0 : value}%</Text>
          </View>
        </View>
        
        <View className={styles.control}>
          {/* <View className={`${styles.controlItem} ${styles.custdown}`} onClick={open}>
            <Image src={res.custdown} className={styles.icon}></Image>
          </View> */}
          <View className={`${styles.switch} ${power ? styles.powerOn : '' }`} onClick={handlePower}>
              <Image src={res.switch_on} className={styles.icon}></Image>
          </View>
          {/* <View className={`${styles.controlItem} ${styles.setting}`}>
            <Image src={res.setting} className={styles.icon}></Image>
          </View> */}
        </View>
      </View>
      <CountdownActionSheet
        show={show}
        value={countdown}
        title="Title"
        cancelText="Cancel"
        okText="Confirm"
        startText="Start"
        hourText="Hour"
        minuteText="Minute"
        countdownCloseText="close countdown"
        countdownCloseTipText="close countdown tip"
        onClickOverlay={hide}
        onCancel={hide}
        onStop={handleStop}
        onOk={handleOK}
      />
    </View>
  );
}

export default Home;
